package com.biaslock;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

/**
 * @author 罗俊华
 * @date 2021/9/6 - 10:31 上午
 */
@Slf4j
public class CompetitionUpgradeBiasLock {

    static final Object lock = new Object();

    /**
     * 测试由锁竞争而导致的偏向锁升级
     * -XX:BiasedLockingStartupDelay=0 -Djol.tryWithSudo=true
     *
     * @param args
     */
    public static void main(String[] args) {


        new Thread(() -> {

            log.debug("初始状态：{}", ClassLayout.parseInstance(lock).toPrintable());

            synchronized (lock) {
                log.debug("临界区内：{}", ClassLayout.parseInstance(lock).toPrintable());
            }

            log.debug("退出临界区：{}", ClassLayout.parseInstance(lock).toPrintable());

            synchronized (CompetitionUpgradeBiasLock.class) {
                CompetitionUpgradeBiasLock.class.notify();
            }
        }, "t1").start();


        new Thread(() -> {
            synchronized (CompetitionUpgradeBiasLock.class) {
                try {
                    CompetitionUpgradeBiasLock.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


            log.debug("开始运行：{}", ClassLayout.parseInstance(lock).toPrintable());

            synchronized (lock) {

                log.debug("临界区内：{}", ClassLayout.parseInstance(lock).toPrintable());
            }

            log.debug("退出临界区：{}", ClassLayout.parseInstance(lock).toPrintable());


        }, "t2").start();
    }
}
